package top.foxhome.web.spiders.download;

import top.foxhome.web.spiders.Config;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.Base64;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 文件下载管理器
 */
public class DownloadManager {

    /**
     * 定义线程池
     */
    ExecutorService fixedThreadPool = Executors.newFixedThreadPool(Config.DOWNLOAD_THREAD_COUNT);

    /**
     * 执行文件下载
     *
     * @param url
     * @param path
     * @param fileName
     */
    public void download(String url, String path, String fileName) {
        fixedThreadPool.execute(() -> downloadImp(url, path, fileName));
    }

    /**
     * 下载base 64格式数据
     * @param base64Data
     * @param path
     * @param fileName
     */
    public void downloadBase64Date(String base64Data, String path, String fileName) {
        fixedThreadPool.execute(() -> downloadBase64DateImp(base64Data, path, fileName));
    }

    private void downloadBase64DateImp(String base64Data, String path, String fileName) {
        String base64Image = base64Data.split(",")[1];
        File pathFile = new File(path);
        if (!pathFile.exists())
            pathFile.mkdirs();
        File saveFile = new File(path, fileName);
        try {
            // 将 base64 数据解码为字节数组
            byte[] imageBytes = Base64.getDecoder().decode(base64Image);
            ByteArrayInputStream bis = new ByteArrayInputStream(imageBytes);
            byte[] bs = new byte[1024];
            int len;
            FileOutputStream os = new FileOutputStream(saveFile, true);
            while ((len = bis.read(bs)) != -1) {
                os.write(bs, 0, len);
            }
            os.close();
            bis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 下载文件实现
     *
     * @param downLoadUrl
     * @param path
     * @param fileName
     */
    private void downloadImp(String downLoadUrl, String path, String fileName) {
        File pathFile = new File(path);
        if (!pathFile.exists())
            pathFile.mkdirs();
        File saveFile = new File(path, fileName);
        try {
            URL url = new URL(downLoadUrl);
            URLConnection con = url.openConnection();
            con.setConnectTimeout(30000);
            con.setReadTimeout(30000);
            InputStream is = con.getInputStream();
            byte[] bs = new byte[1024];
            int len;
            FileOutputStream os = new FileOutputStream(saveFile, true);
            while ((len = is.read(bs)) != -1) {
                os.write(bs, 0, len);
            }
            os.close();
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
